
package com.kweative.lingua.server.structures;

import com.kweative.cluster.Cluster;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class DataStore<K,V> implements Serializable {
    private Map<K,V> store;
    private String identifier;
    public DataStore(String identifier) {
        this.identifier = identifier;
        store = new HashMap<K, V>();
        Cluster.store(identifier,(Serializable)store);
        Logger.getAnonymousLogger().log(Level.INFO,String.format("Initialized datastore at '%s'",identifier));
    }
    public void put(K key,V value) {
        if (!has(key))
            store.put(key, value);
        Cluster.store(identifier,(Serializable)store);
    }
    public V get(K key) {
        if (has(key))
            return store.get(key);
        return null;
    }
    /**
     * Get value - and if not present - insert defaultValue and return that
     * @param key
     * @param defaultValue
     * @return Object
     */
    public V get(K key,V defaultValue) {
        if (has(key))
            return store.get(key);
        store.put(key, defaultValue);
        return defaultValue;
    }
    public boolean has(K key) {
        return store.containsKey(key);
    }
    public void remove(K key) {
        store.remove(key);
        Cluster.store(identifier,(Serializable)store);
    }
    public Map<K,V> map() {
        return store;
    }
}
